// pages/client/valet-order/valet-order.js
import {
  formatTime
} from '../../../utils/util'
import {
  getValetList,
  sendOrderInfo
} from '../../../network/client'
import {
  debounce,
  toast,
  throttle
} from '../../../utils/Tools'
let years = []
let months = []
let days = []
for (let i = new Date().getFullYear(); i <= new Date().getFullYear() + 1; i++) {
  years.push(i)
}
for (let i = 1; i <= 12; i++) {
  months.push(i)
}
for (let i = 1; i <= 31; i++) {
  days.push(i)
}
Page({
  data: {
    steps: [{
        desc: '基本信息'
      },
      {
        desc: '添加商品'
      },
      {
        desc: '下单信息'
      }
    ],
    active: 0,
    orderDate: null,
    // 选择客户
    clientArr: [],
    client: null,

    // 出货公司
    companyArr: {},
    company: null,
    // 供应商
    supplyArr: ['请先选择出货公司'],
    supply: null,
    // 出货点
    pointArr: ['请先选择出货公司'],
    point: null,
    // 项目名称
    project_name: '',

    //  添加商品列表
    goodsList: [{
      product_name: null,
      norms: null,
      package: null,
      count: null,
      money: null,
      product_nameKey: {
        value: null,
        arr: ['请先选择出货点']
      },
      normsKey: {
        value: null,
        arr: ['请先选择出货点']
      },
      packageKey: {
        value: null,
        arr: ['请先选择出货点']
      },
      unit_nameKey: {
        value: null,
        arr: ['请先选择出货点']
      },
      status: 'add'
    }],
    // 添加商品
    shopCate: [],
    goodsCate: {},
    years,
    months,
    days,
    time: ['上午', '中午', '下午'],
    date: '选择要求送达时间',
    currentDate: null,
    // 提货方式
    // takeWay: '2',
    // 车牌号
    // carNum: '',
    // isCarNum: false,
    // 卸货地点
    place: ['广东省', '广州市', '天河区'],
    // 要求送达时间
    isDate: false,
    dateTime: null,
    minDate: new Date().getTime(),
    // 详细地址
    detailAddress: null,
    // 收货人名称
    receiver: null,
    phone: null,
    bill: "1",
    // 备注
    mark: null,
    isSubmit: true,
    code: '',
    orderList:{},
    order_id:'',
  },
  async onLoad(options) {
    const month = new Date().getMonth()
    const date = new Date().getDate() - 1
    //       调用网络请求      //
    await this._getValetList()
    let orderLists={}
    if(options.orderList){
      orderLists=JSON.parse(options.orderList)
      this.setData({
        orderList:orderLists
      })
    }
    if (this.data.clientArr.length > 0 && (options.customer_id? options.customer_id:orderLists.customer_id)) {
      this.data.clientArr.forEach((res, i) => {
        if (res.id == (options.customer_id?options.customer_id:orderLists.customer_id)) {
          this.setData({
            client: i,
          })
          return
        }
      })
    }
    this.setData({
      orderDate: formatTime(new Date()),
      currentDate: [0, month, date],
      code: options.supplyer_company?options.supplyer_company:orderLists.supplyer_company
    })
    console.log(orderLists)
    this.handleFormInput = debounce(this.handleFormInput, 100)
    if(orderLists.customer_id){
      let companyArr = this.data.companyArr;
      let shopCate = this.data.shopCate;
      let goodCompany = companyArr.name.indexOf(orderLists.company_name);
      // console.log(goodCompany)
      let product=[];
      for (var a in companyArr) {
        if (a ==orderLists.company_name) {
          for (var b in companyArr[a]) {
            // console.log(b)
            if (b == orderLists.supplyer_company) {
              // ["广州南区/番水库", "广州东区/集成库", "广州南区/弘海库", "广州南区/滘心库"]
              //0
              var pool = shopCate[companyArr[a].supplyer_company[companyArr[a].supplyer_company.indexOf(orderLists.supplyer_company)]][companyArr[a][b][companyArr[a][b].indexOf(orderLists.pay_address) + '']]
              // console.log(pool)
              let abc=pool.product_name[0];
              let def={}
              for(var keys in pool){
                if(keys===abc){
                  def=pool[keys]
                }
              }
              // console.log(def)
              var nromsIndex=def.pack_method.findIndex(value=>value==orderLists.pack_method)
              var standardsIndex=def.standards.findIndex(value=>value==orderLists.standards)
              product=[{"product_name":orderLists.product_name,
              "norms":orderLists.standards,
              "package":orderLists.pack_method,
              "count":Number(orderLists.product_num),
              "money":orderLists.unit_price,
              "product_nameKey":{"value":"0","arr":pool.product_name},
              "normsKey":{"value":standardsIndex,"arr":def.standards},
              "unit_nameKey":{"value":'0',"arr":["吨"]},
              "packageKey":{"value":nromsIndex,"arr":def.pack_method},
              "status":"add",
              "unit_name":"吨"
            }]
            // console.log(product)
              this.setData({
                bill:orderLists.bill + '',
                phone:orderLists.take_phone,
                receiver:orderLists.take_name,
                date:orderLists.end_time,
                mark:orderLists.servicer_mark,
                detailAddress:orderLists.get_address,
                place:orderLists.get_position,
                project_name:orderLists.project_name,
                company: goodCompany,
                supplyArr: companyArr[a].supplyer_company,
                supply: companyArr[a].supplyer_company.indexOf(orderLists.supplyer_company),
                pointArr: companyArr[a][b],
                point: companyArr[a][b].indexOf(orderLists.pay_address) + '',
                goodsCate: pool,
                goodsList:product,
              })
            }
          }
        }
      }
    }else{
      // console.log('222222222222')
    }
    // var valetMessage = wx.getStorageSync('valetContent');
    // console.log(valetMessage)
    // if (valetMessage.length > 0) {
    //   valetMessage.forEach(item => {
    //     if (item.id == options.customer_id) {
    //       console.log(item)
    //       var aa = item.data;
    //       var dd = JSON.parse(aa.product);
    //       console.log(dd)
    //       this.goodsList = dd[0];
    //       //出货公司 companyArr:res.data.pay_name, clientArr: res.data.customer,shopCate: res.data.product
    //       let companyArr = this.data.companyArr;
    //       let shopCate = this.data.shopCate;
    //       var goodCompany = companyArr.name.indexOf(aa.pay_name);
    //       for (var a in companyArr) {
    //         if (a == aa.pay_name) {
    //           console.log(a)
    //           console.log(companyArr[a])
    //           for (var b in companyArr[a]) {
    //             // console.log(b)
    //             if (b == aa.supplyer_company) {
    //               // ["广州南区/番水库", "广州东区/集成库", "广州南区/弘海库", "广州南区/滘心库"]
    //               //0
    //               var pool = shopCate[companyArr[a].supplyer_company[companyArr[a].supplyer_company.indexOf(aa.supplyer_company)]][companyArr[a][b][companyArr[a][b].indexOf(aa.pay_address) + '']]
    //               console.log(pool)
    //               let abc=pool.product_name[0];
    //               let def={}
    //               for(var keys in pool){
    //                 if(keys===abc){
    //                   def=pool[keys]
    //                 }
    //               }
    //               console.log(def)
    //               var nromsIndex=def.pack_method.findIndex(value=>value=="袋装")
    //               var standardsIndex=def.standards.findIndex(value=>value=="M32.5")
    //               console.log(nromsIndex,standardsIndex)
    //               this.setData({
    //                 project_name: aa.site_address,
    //                 company: goodCompany,
    //                 supplyArr: companyArr[a].supplyer_company,
    //                 supply: companyArr[a].supplyer_company.indexOf(aa.supplyer_company),
    //                 pointArr: companyArr[a][b],
    //                 point: companyArr[a][b].indexOf(aa.pay_address) + '',
    //                 goodsCate: pool,
    //                 goodsList: dd,
    //                 place: JSON.parse(aa.get_position),
    //                 detailAddress: aa.get_address,
    //                 receiver: aa.take_name,
    //                 phone: aa.take_phone,
    //                 date: aa.end_time,
    //                 bill: aa.bill,
    //                 mark: aa.mark,
    //               })
    //             }
    //           }
    //         }
    //       }

    //     }
    //   })
    // }
  },
  //         事件函数         //
  handleIfChangeNav() { // 处理点击了进度条
    // console.log(this.data.active)
    if (this.data.active === 0) {
      // console.log(this.data.project_name, typeof (this.data.point))
      if (!this.data.project_name || !this.data.point) {
        return 'false';
      }
    } else {
      if (!this.data.goodsList[0].unit_name || !this.data.goodsList[0].count || !this.data.goodsList[0].money) {
        return 'false';
      }
    }
  },
  handleStep() { //   处理点击下一步
    const bool = this.handleIfChangeNav()
    if (bool === 'false') return;
    const active = ++this.data.active
    this.setData({
      active
    })
  },
  handleActive(e) { // 处理点击进步条
    const bool = this.handleIfChangeNav()
    if (bool === 'false' && this.data.active < e.detail) return;
    this.setData({
      active: e.detail
    })
  },
  handleAddGoods(e) { //   处理点击添加商品
    const {
      status,
      index
    } = e.currentTarget.dataset
    switch (status) {
      case 'add':
        const goodsList = this.data.goodsList.concat({
          product_name: null,
          norms: null,
          package: null,
          count: null,
          money: null,
          product_nameKey: {
            value: null,
            arr: []
          },
          normsKey: {
            value: null,
            arr: []
          },
          packageKey: {
            value: null,
            arr: []
          },
          unit_nameKey: {
            value: null,
            arr: ['请先选择出货点']
          },
          status: 'delete'
        })
        this.setData({
          goodsList
        })
        break;
      case 'delete':
        if (this.data.goodsList.length <= 1) {
          wx.showToast({
            title: '至少输入一个商品',
            icon: 'none'
          });
          return;
        };
        this.data.goodsList.splice(index, 1);
        this.setData({
          goodsList: this.data.goodsList
        })
        break;
    }
  },
  handleGoodsSele() {
    if (this.data.point === null) {
      toast('请先选择出货点', 'none', 1000)
      return;
    }
  },
  handleChangeGoods(e) { //  修改添加商品的值
    const {
      type,
      index
    } = e.currentTarget.dataset
    const key = `goodsList[${index}].${type}Key.value`
    const value = `goodsList[${index}].${type}`
    this.setData({
      [key]: e.detail.value,
      [value]: this.data.goodsList[index][`${type}Key`].arr[e.detail.value]
    })
    if (type === 'product_name') {
      const result = this.data.goodsCate[this.data.goodsCate.product_name[e.detail.value]]
      this.setData({
        [`goodsList[${index}].product_name`]: this.data.goodsCate.product_name[e.detail.value],
        [`goodsList[${index}].product_nameKey.arr`]: this.data.goodsCate.product_name,
        [`goodsList[${index}].normsKey.arr`]: result.standards,
        [`goodsList[${index}].packageKey.arr`]: result.pack_method,
        [`goodsList[${index}].unit_nameKey.arr`]: result.unit_name,
        [`goodsList[${index}].normsKey.value`]: null,
        [`goodsList[${index}].unit_nameKey.value`]: null,
        [`goodsList[${index}].packageKey.value`]: null
      })
    }
    if (type === "norms") this.setData({
      [`goodsList[${index}].packageKey.value`]: null,
      [`goodsList[${index}].unit_nameKey.value`]: null
    })
    if (type === 'package') this.setData({
      [`goodsList[${index}].unit_nameKey.value`]: null
    })
  },
  handleInputGoods(e) {
    const {
      type,
      index
    } = e.currentTarget.dataset
    const value = `goodsList[${index}].${type}`
    this.setData({
      [value]: e.detail.value
    })
  },
  handleFormInput(e) { //  处理表单输入框输入
    const value = e.currentTarget.dataset.type
    this.setData({
      [value]: e.detail.value
    })
  },
  // handleCarNum(e){ //处理自提车牌号的显隐
  //   if(this.data.takeWay !== '1') return
  //   this.setData({
  //     isCarNum: true
  //   })
  // },
  // handleCarComfirm(e){  //处理点击自提车牌号确定
  //   this.setData({
  //     takeWay:"1",
  //     isCarNum: false
  //   })
  // },
  handleRadio(e) { //处理单选框选择
    this.setData({
      bill: e.detail
    })
  },
  // onInput(e){ // 隐藏popup
  //   const date = moment(e.detail,"YYYY-MM-DD")
  //   this.setData({dateTime:e.detail,date,isDate:false})
  // },

  onClose() { // 处理自提车牌号的隐藏
    this.setData({
      // isCarNum: false,
      // takeWay: '2',
      isDate: false
    })
  },
  bindChange(e) {
    let val = e.detail.value
    this.setData({
      date: `${this.data.years[val[0]]}年${this.data.months[val[1]]}月${this.data.days[val[2]]}日 ${this.data.time[val[3]]}`
    })
  },
  handlePopupShow(e) { // 显示popup
    this.setData({
      isDate: true
    })
  },
  handleChange(e) { // 处理选择客户数据
    const {
      type: value
    } = e.currentTarget.dataset
    this.setData({
      [value]: e.detail.value
    })
    if (value === 'company') this.setData({
      supplyArr: this.data.companyArr[this.data.companyArr.name[e.detail.value]].supplyer_company,
      supply: null,
      point: null
    })
    if (value === 'supply') {
      const supply = this.data.companyArr[this.data.companyArr.name[this.data.company]]
      this.setData({
        pointArr: supply[this.data.supplyArr[this.data.supply]],
        point: null
      })
    }
    if (value === 'point') {
      this.setData({
        goodsCate: this.data.shopCate[this.data.supplyArr[this.data.supply]][this.data.pointArr[this.data.point]]
      })
      this.data.goodsList.forEach(res => {
        res.product_nameKey.value = null
        res.normsKey.value = null
        res.packageKey.value = null
        res.unit_nameKey.value = null
        this.setData({
          goodsList: this.data.goodsList
        })
      })
    }
  },
  bindRegionChange: function (e) { // 处理卸货地点
    this.setData({
      place: e.detail.value
    })
  },
  handleSubmit() {
    if (this.data.isSubmit) {
      this.data.isSubmit = false
      const data = {
        order_time: this.data.orderDate,
        customer_id: this.data.clientArr[this.data.client].id, //  客户ID
        client_name: this.data.clientArr[this.data.client].customer_name, // 客户名称
        end_time: this.data.date || '', // 选择到达日期
        // car_info: this.data.carNum || '', // 车牌号
        product: JSON.stringify(this.data.goodsList), // 选择商品
        site_address: this.data.project_name, //  项目名称
        get_position: JSON.stringify(this.data.place) || '', //选择地址
        get_address: this.data.detailAddress || '', // 详细地址
        take_name: this.data.receiver || '', // 收货人
        take_phone: this.data.phone || '', // 收货人电话,
        supplyer_company: this.data.supplyArr[this.data.supply],
        pay_name: this.data.companyArr.name[this.data.company],
        pay_address: this.data.pointArr[this.data.point],
        bill: this.data.bill,
        mark: this.data.mark || '' //  备注
      }
      if (data.customer_id && data.product.length > 0 && data.pay_name && data.supplyer_company && data.site_address && data.pay_address) {
        sendOrderInfo(data).then(res => {
          this.data.isSubmit = true
          console.log("下单成功",res)
          if (res.code === 200) {
            toast('上传成功', 'success')
            //先获取下单的数据
            // var valetContent = wx.getStorageSync('valetContent');
            // // console.log(valetContent, '1231133232')
            // if (valetContent == '') {
            //   var idData = [{
            //     id: this.data.clientArr[this.data.client].id,
            //     data: data
            //   }];
            //   wx.setStorageSync('valetContent', idData);
            // } else if (valetContent.length > 0) {
            //   valetContent.forEach((item) => {
            //     if (item.id == this.data.clientArr[this.data.client].id) {
            //       item.data = data
            //       wx.setStorageSync('valetContent', valetContent);
            //       // console.log(item.data)
            //       // console.log(valetContent,'直接替代')
            //     } else {
            //       valetContent.push({
            //         id: this.data.clientArr[this.data.client].id,
            //         data: data
            //       })
            //       wx.setStorageSync('valetContent', valetContent);
            //       // console.log(valetContent,'添加进去')
            //     }
            //   })
            // }
            setTimeout(() => {
              if (this.data.code == "未签") {
                wx.reLaunch({
                  url: '/pages/client/contract-status/contract-status'
                });
              } else {
                wx.switchTab({
                  url: '/pages/client/client/client'
                });
              }

            }, 1500)
          } else {
            // toast(msg + '填写上传失败,请稍后重试!')
            // console.log('下单四百121',res.msg)
            toast(res.msg)
          }
        }).catch(err => {
          this.data.isSubmit = true
          // toast('上传失败,请稍后重试!')
          // console.log(err.msg,'hhhh')
          toast(err.msg)
        })
      } else {
        toast('请注意填写不要留空')
      }
    }
  },
  //         网络请求         //
  async _getValetList() {
    const res = await getValetList()
    // console.log(res)
    if (res.data.customer.length > 0) {
      this.setData({
        clientArr: res.data.customer,
        companyArr: res.data.pay_name,
        shopCate: res.data.product
      })
    } else {
      toast('没有客户，请先添加客户')
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/client/client/client'
        });
      }, 1000)
    }
  }
})